<template>
  <div class="wms-inventory-page art-full-height">
    <!-- 搜索栏 -->
    <WmsInventorySearch
      v-model:filter="searchFilter as any"
      @search="handleSearch"
      @reset="handleReset"
    />

    <ElCard class="art-table-card" shadow="never">
      <!-- 表格工具栏 -->
      <ArtTableHeader
        v-model:columns="columnChecks as any"
        @refresh="refreshData"
        layout="refresh,size,fullscreen,columns,settings"
      >
        <template #left>
          <ElButton type="primary" @click="showAdjustDialog" v-ripple>
            <ElIcon><Edit /></ElIcon>
            库存调整
          </ElButton>
          <ElButton @click="showAllocateDialog" v-ripple>
            <ElIcon><Connection /></ElIcon>
            库存分配
          </ElButton>
          <ElButton @click="handleExport" v-ripple>
            <ElIcon><Download /></ElIcon>
            导出
          </ElButton>
          <ElButton @click="showHistoryDialog" v-ripple>
            <ElIcon><Clock /></ElIcon>
            库存历史
          </ElButton>
        </template>
      </ArtTableHeader>

      <!-- 表格 -->
      <ArtTable
        :loading="isLoading"
        :data="tableData"
        :columns="columns as any"
        :pagination="paginationState as any"
        @selection-change="(selection: any) => (selectedRows = selection)"
        @pagination:size-change="onPageSizeChange"
        @pagination:current-change="onCurrentPageChange"
      >
        <!-- 自定义列插槽 -->
        <template #warehouseInfo="{ row }">
          <div class="location-info">
            <div class="warehouse-name">{{ row.warehouseName }}</div>
            <div class="area-name">{{ row.areaName }}</div>
          </div>
        </template>

        <template #itemInfo="{ row }">
          <div class="item-info">
            <div class="item-name">{{ row.itemName }}</div>
            <div class="item-code">{{ row.itemCode }}</div>
            <div class="sku-info">
              <ElTag size="small">{{ row.skuName }}</ElTag>
            </div>
          </div>
        </template>

        <template #quantityInfo="{ row }">
          <div class="quantity-info">
            <div class="total-quantity">
              <ElStatistic
                :value="row.quantity || 0"
                :precision="3"
                suffix="件"
              />
            </div>
            <div class="allocated-quantity" v-if="row.allocatedQuantity > 0">
              <ElTag type="warning" size="small">
                已分配: {{ row.allocatedQuantity }}
              </ElTag>
            </div>
            <div class="available-quantity">
              <ElTag type="success" size="small">
                可用: {{ (row.quantity || 0) - (row.allocatedQuantity || 0) }}
              </ElTag>
            </div>
          </div>
        </template>

        <template #batchInfo="{ row }">
          <div class="batch-info">
            <div class="batch-no" v-if="row.batchNo">
              <ElTag type="info" size="small">{{ row.batchNo }}</ElTag>
            </div>
            <div class="expiration-date" v-if="row.expirationDate">
              <ElText
                size="small"
                :type="getExpirationStatus(row.expirationDate)"
              >
                {{ formatDate(row.expirationDate) }}
              </ElText>
            </div>
          </div>
        </template>

        <template #actions="{ row }">
          <ElButton type="primary" link @click="handleViewDetail(row)">
            <ElIcon><View /></ElIcon>
            详情
          </ElButton>
          <ElButton type="warning" link @click="handleAdjust(row)">
            <ElIcon><Edit /></ElIcon>
            调整
          </ElButton>
          <ElButton type="info" link @click="handleViewHistory(row)">
            <ElIcon><Clock /></ElIcon>
            历史
          </ElButton>
        </template>
      </ArtTable>
    </ElCard>

    <!-- 库存调整弹窗 -->
    <WmsInventoryAdjustDialog
      v-model:visible="adjustDialogVisible"
      :inventory-data="currentInventoryData"
      @submit="handleAdjustDialogSubmit"
    />

    <!-- 库存分配弹窗 -->
    <WmsInventoryAllocateDialog
      v-model:visible="allocateDialogVisible"
      :selected-rows="selectedRows"
      @submit="handleAllocateDialogSubmit"
    />

    <!-- 库存历史弹窗 -->
    <WmsInventoryHistoryDialog
      v-model:visible="historyDialogVisible"
      :inventory-data="currentInventoryData"
    />

    <!-- 库存详情弹窗 -->
    <WmsInventoryDetailDialog
      v-model:visible="detailDialogVisible"
      :inventory-data="currentInventoryData"
    />
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { useTable } from "@/composables/useTable";
import { WmsInventoryService } from "@/api/wms/inventoryApi";
import { ElMessage } from "element-plus";
import {
  Edit,
  Download,
  Clock,
  Connection,
  View,
} from "@element-plus/icons-vue";
import { formatDate } from "@/utils/dateUtils";

// 导入子组件
import WmsInventorySearch from "./components/WmsInventorySearch.vue";
import WmsInventoryAdjustDialog from "./components/WmsInventoryAdjustDialog.vue";
import WmsInventoryAllocateDialog from "./components/WmsInventoryAllocateDialog.vue";
import WmsInventoryHistoryDialog from "./components/WmsInventoryHistoryDialog.vue";
import WmsInventoryDetailDialog from "./components/WmsInventoryDetailDialog.vue";

defineOptions({ name: "WmsInventory" });

// 表格配置
const columns: any[] = [
  { type: "selection", width: 50 },
  {
    prop: "warehouseInfo",
    label: "仓库/库区",
    slot: "warehouseInfo",
    minWidth: 150,
  },
  {
    prop: "itemInfo",
    label: "商品信息",
    slot: "itemInfo",
    minWidth: 200,
  },
  {
    prop: "quantityInfo",
    label: "库存数量",
    slot: "quantityInfo",
    minWidth: 150,
  },
  {
    prop: "batchInfo",
    label: "批次信息",
    slot: "batchInfo",
    minWidth: 120,
  },
  {
    prop: "updateTime",
    label: "更新时间",
    width: 160,
    formatter: (row: any) => formatDate(row.updateTime),
  },
  {
    prop: "actions",
    label: "操作",
    slot: "actions",
    width: 180,
    fixed: "right",
  },
];

// 使用表格组合式函数
const {
  data: tableData,
  loading: isLoading,
  pagination: paginationState,
  query: searchFilter,
  loadData: refreshData,
  search: handleSearch,
  resetQuery: handleReset,
  handlePageChange,
} = useTable<WMS.Inventory.InventoryInfo>({
  fetchApi: async (params: any) => {
    const response = await WmsInventoryService.getInventoryList(params);
    return {
      data: response.data?.rows || [],
      total: response.data?.total || 0,
    };
  },
  initialQuery: {},
  immediate: true,
});

// 分页大小变化处理
const onPageSizeChange = (pageSize: number) => {
  handlePageChange(1, pageSize);
};

// 分页变化处理
const onCurrentPageChange = (page: number, pageSize?: number) => {
  handlePageChange(page, pageSize || paginationState.value.limit);
};

// 列显示控制
const columnChecks = ref(columns.map(() => ({})));

// 弹窗状态
const adjustDialogVisible = ref(false);
const allocateDialogVisible = ref(false);
const historyDialogVisible = ref(false);
const detailDialogVisible = ref(false);
const currentInventoryData = ref<WMS.Inventory.InventoryInfo | null>(null);

// 选中的行
const selectedRows = ref<WMS.Inventory.InventoryInfo[]>([]);

// 显示库存调整弹窗
const showAdjustDialog = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请先选择要调整的库存记录");
    return;
  }
  if (selectedRows.value.length > 1) {
    ElMessage.warning("一次只能调整一条库存记录");
    return;
  }
  currentInventoryData.value = selectedRows.value[0];
  adjustDialogVisible.value = true;
};

// 显示库存分配弹窗
const showAllocateDialog = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请先选择要分配的库存记录");
    return;
  }
  allocateDialogVisible.value = true;
};

// 显示库存历史弹窗
const showHistoryDialog = () => {
  historyDialogVisible.value = true;
};

// 查看库存详情
const handleViewDetail = (row: WMS.Inventory.InventoryInfo) => {
  currentInventoryData.value = row;
  detailDialogVisible.value = true;
};

// 调整库存
const handleAdjust = (row: WMS.Inventory.InventoryInfo) => {
  currentInventoryData.value = row;
  adjustDialogVisible.value = true;
};

// 查看库存历史
const handleViewHistory = (row: WMS.Inventory.InventoryInfo) => {
  currentInventoryData.value = row;
  historyDialogVisible.value = true;
};

// 处理库存调整弹窗提交
const handleAdjustDialogSubmit = () => {
  adjustDialogVisible.value = false;
  refreshData();
};

// 处理库存分配弹窗提交
const handleAllocateDialogSubmit = () => {
  allocateDialogVisible.value = false;
  refreshData();
};

// 导出数据
const handleExport = async () => {
  try {
    ElMessage.info("导出功能开发中");
    // TODO: 实现导出功能
    // const response = await WmsInventoryService.exportInventoryData(searchFilter.value as any);
    // 处理文件下载
  } catch (_error) {
    ElMessage.error("导出失败");
  }
};

// 获取过期状态
const getExpirationStatus = (expirationDate: string) => {
  if (!expirationDate) return "info";

  const expDate = new Date(expirationDate);
  const now = new Date();
  const diffDays = Math.ceil(
    (expDate.getTime() - now.getTime()) / (1000 * 60 * 60 * 24),
  );

  if (diffDays < 0) return "danger"; // 已过期
  if (diffDays <= 7) return "warning"; // 7天内过期
  if (diffDays <= 30) return "primary"; // 30天内过期
  return "success"; // 正常
};
</script>

<style lang="scss" scoped>
.wms-inventory-page {
  .location-info {
    .warehouse-name {
      font-weight: 500;
      color: var(--el-text-color-primary);
      margin-bottom: 4px;
    }

    .area-name {
      font-size: 12px;
      color: var(--el-text-color-regular);
    }
  }

  .item-info {
    .item-name {
      font-weight: 500;
      color: var(--el-text-color-primary);
      margin-bottom: 4px;
    }

    .item-code {
      font-size: 12px;
      color: var(--el-text-color-regular);
      margin-bottom: 4px;
    }

    .sku-info {
      margin-top: 4px;
    }
  }

  .quantity-info {
    .total-quantity {
      margin-bottom: 8px;
    }

    .allocated-quantity,
    .available-quantity {
      margin-bottom: 4px;
    }
  }

  .batch-info {
    .batch-no {
      margin-bottom: 4px;
    }

    .expiration-date {
      font-size: 12px;
    }
  }
}
</style>
